<template>
    <div class="tree-main">
        <div>顶级节点</div>
        <TreeRow :list="treeData" :curret1="curret1" @select="emitData" @check="getCheckedList"></TreeRow>
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, PropType } from "vue";
import TreeRow from "./TreeRow.vue";
import { TreeItem } from './types';
export default defineComponent({
    components: { TreeRow },
    name: "Tree",
    emits: {
        select: null
    },
    props: {
        list: {
            type: Array as PropType<TreeItem[]>,
            default: () => []
        },
        getChildren: {
            type: Function,
            default: function (treeList: string[]) {

            },
        }
    },
    setup(props: { list: TreeItem[] }) {
        const treeData = ref<TreeItem[]>([])
        const curret1 = ref<string>()
        const list = JSON.parse(JSON.stringify(props.list))
        list.forEach((item: TreeItem) => {
            item.parentId = item.parentId || "0"
            item.allowChecked = true
            item.checked = true
            
            function setChild(item: TreeItem) {
                // 一开始有没有children
                let isNoChildren = false
                if (!item.children) {
                    item.children = []
                    isNoChildren = true
                }

                list.forEach((x: TreeItem) => {
                    if (item.id == x.parentId) {
                        setChild(x)
                        item.children?.push(x)
                    }
                })
                if (isNoChildren && item.children.length < 1) delete item.children
            }
            if (item.parentId == 0) {
                treeData.value.push(item)
                setChild(item)
            }
        })
        function emitData(item: TreeItem) {
            curret1.value = item[item.length - 1].id
        }
        
        function getCheckedList() {
            const allList: Array<string|number>[] = []
            function getChecked(list: TreeItem[], index: number) {
                list?.forEach(x => {
                    if (x.checked) {
                        if (allList[index]) {
                            allList[index].push(x.id)
                        } else {
                            allList[index] = [x.id]
                        }
                    }
                    if(x.children){
                        getChecked(x.children,index+1)
                    }
                })
            }

            getChecked(treeData.value, 0)
            console.log(allList);
            

        }
        getCheckedList()
        return {
            treeData,
            curret1,
            emitData,
            getCheckedList
        };
    },
});
</script> 
<style scoped lang="less">
.tree-main {
    overflow: hidden;
    width: 200px;
    margin: 0 auto;
    font-size: 12px;
}
</style>
